import pymongo
from pymongo import MongoClient
import datetime
from bson import BSON

class Storage:    
    def __init__(self, IP="140.112.170.32"):
        self.client = None
        self.post = None
        self.post_id=None
        self.posts = None
        self.db = None
        self.collection = None
        self.ip=IP
        self.post_device=None
        self.bson_device=None

        self.post_sensor=None
        post_id_s=None
        print self.ip
        
                  
    def CreateSystem(self):
        self.client = MongoClient(self.ip, 27017)
        self.db = self.client["wukong"]
        self.collection = self.db["readings"]
        print 'connected.'




    def retrieve(self):
        for p in self.db.readings.find() :
            print '[All]+%s'%(p)

    def retrieve_sensor(self,n_id,pt):
        for p in self.db.readings.find({ 'node_id':n_id , 'port':pt }) :
            print '[Specific Sensor]+%s'%(p)

    def retrieve_time(self,t1,t2):
        for p in self.db.readings.find( { 'timestamp':  { "$gte":t1 , "$lt": t2 } } ) :
            print '[Specific time]+%s'%(p)

st=Storage("140.112.170.32")
#st=Storage("127.0.0.1")
st.CreateSystem()
#st.retrieve()
st.retrieve_sensor(9,3)
#st.retrieve_time(20140917161326,20140917161328)

'''
    def AddDevice(houseId, Device):
    def AddSensor(houseId, deviceId, Sensor):
    def AddActuator(houseId, deviceId, Actuator):
    def StoreSensorData(SensorData):
    def StorageContextData(ContextData):
    def FetchSensorDataInTimeRange(...):
    def FetchSensorDataInLocation(...):
    def FetchSensorData(...):
   '''

'''
    def bson_device(self,Device) : #instead of JSON, is it protobuf? #it seems like it will sort title automatically??
        self.bson_device = BSON.encode({"mac_address": "%s_addr" %(Device),
        "SystemParameter" : "parameters",
        "Sensor" : "sensors",
        "Actuator" : "actuators"
        })
        #print bson_string.decode()

'''